package com.sk.weichat.ui.groupchat;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.GroupMembersHeadAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.dialog.DeleteMemberDialog;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.SearchUtils;
import com.sk.weichat.util.SearchUtils.onItemClickOListener;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.BannedDialog;
import com.sk.weichat.view.circularImageView.CircularImageVIew;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.CHANGE_RESULT;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.REMARKNAME;

/**
 * @ 群成员列表
 * create by swy 2019-10-14
 */
public class GroupSendAtListActivity extends BaseActivity implements View.OnClickListener {

    public static final String EXTRA_ROOM_MEMBER = "roomMember";
    private LinearLayout mLlMain;
    private RelativeLayout mRlSearch;
    private RelativeLayout mRlTitle;

    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private SideBar mSideBar;
    private TextView mTextDialog;

    private List<BaseSortModel<RoomMember>> mSortRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> mSortHeadRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> sortedList;


    private String mRoomId = "";
    private View mHeadView;
    private String mRoomJid = "";
    private int mRole;

    private GroupMerbersAdapter mAdapter;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private CircularImageVIew mImgEveryone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_members_list);

        mRoomId = getIntent().getStringExtra("roomId");
        mRoomJid = getIntent().getStringExtra("roomJid");
        mRole = getIntent().getIntExtra("role",0);
        initActionBar();
        initView();
        loadData();

    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        tvTitle.setText(R.string.group_send_at);
    }

    private void initView() {
        mLlMain = findViewById(R.id.ll_main);
        mRlTitle = findViewById(R.id.rt_title);
        mRlSearch = findViewById(R.id.layout_search);
        mRlSearch.setOnClickListener(this);
        mRefreshLayout = findViewById(R.id.refresh_layout);
        mRecyclerView = findViewById(R.id.pull_refresh_list);

        initRefreshLayout();
        initRecycerView();

    }

    private void initRefreshLayout() {
        mRefreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        mRefreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        mRefreshLayout.setEnableLoadMore(false);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mRefreshLayout.finishRefresh();
            }
        });
    }

    private void initRecycerView() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(manager);
        mAdapter = new GroupMerbersAdapter(mSortRoomMember);
        //添加头部
        mHeadView = LayoutInflater.from(this).inflate(R.layout.layout_send_at_head, mRecyclerView, false);

        // mRole  1创建者，2管理员，3成员,   成员不可@全部
        if (mRole!=3){
            mAdapter.addHeaderView(mHeadView);
        }
        mImgEveryone = (CircularImageVIew) mHeadView.findViewById(R.id.everyone_iv);
        mHeadView.findViewById(R.id.ll_everyone_head).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                setResult(MucChatActivity.RESULT_ALL_MEMBER_CODE, intent);
                finish();
            }
        });

        mAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                RoomMember roomMember = mSortRoomMember.get(position).getBean();
                onItemClick(roomMember, position);
            }
        });

        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getSortRoomMembersPositionForSection(mSortRoomMember, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });
    }

    private void loadData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(this, ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            List<RoomMember> data = RoomMemberDao.getInstance().getRoomMember(mRoomId);
            Map<String, Integer> existMap = new HashMap<>();
            sortedList = SortHelper.toSortedModelList(data, existMap, RoomMember::getShowName);
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                if (mSortRoomMember != null) {
                    mSortRoomMember.clear();
                }
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                for (int i = 0; i < sortedList.size(); i++) {
                    if (!sortedList.get(i).getBean().getUserId().equals(CoreManager.getSelf(mContext).getUserId())) {// 移除掉自己
                        mSortRoomMember.add(sortedList.get(i));
                    }
                }
                mAdapter.notifyDataSetChanged();

                List<String> urlS = new ArrayList<>();
                if (mSortRoomMember.size() > 0) {
                    if (mSortRoomMember.size() > 5) {
                        // 群组头像最多为5人组合
                        for (int i = 0; i < 5; i++) {
                            String avatarUrl = AvatarHelper.getAvatarUrl(mSortRoomMember.get(i).getBean().getUserId(), true);
                            urlS.add(avatarUrl);
                        }
                        mImgEveryone.addUrl(urlS);
                    } else {
                        for (int i = 0; i < mSortRoomMember.size(); i++) {
                            String avatarUrl = AvatarHelper.getAvatarUrl(mSortRoomMember.get(i).getBean().getUserId(), true);
                            urlS.add(avatarUrl);
                        }
                        mImgEveryone.addUrl(urlS);
                    }
                }
            });
        });
    }

    @Override
    public void onClick(View v) {
        if (v == mRlSearch) {//搜索
            new SearchUtils(GroupSendAtListActivity.this, mRlTitle,
                    mLlMain, "请输入昵称或备注名", sortedList, new onItemClickOListener() {
                @Override
                public void onSearchItemClick(RoomMember roomMember) {
                    if (roomMember.getRole() == 1 || roomMember.getRole() == 2) {
                        for (int i = 0; i < mSortHeadRoomMember.size(); i++) {
                            if (mSortHeadRoomMember.get(i).getBean().getUserId() == roomMember.getUserId()) {
                                onItemClick(roomMember, i);
                                return;
                            }
                        }
                    } else {
                        for (int i = 0; i < mSortRoomMember.size(); i++) {
                            if (mSortRoomMember.get(i).getBean().getUserId() == roomMember.getUserId()) {
                                onItemClick(roomMember, i);
                                return;
                            }
                        }
                    }
                }
            }).showSearchBar();
        }
    }


    public void onItemClick(RoomMember roomMember, int position) {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_ROOM_MEMBER, JSON.toJSONString(roomMember));
        setResult(RESULT_OK, intent);
        finish();
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private class GroupMerbersAdapter extends BaseQuickAdapter<BaseSortModel<RoomMember>, BaseViewHolder> {
        List<BaseSortModel<RoomMember>> mSortContactList;

        public GroupMerbersAdapter(List<BaseSortModel<RoomMember>> data) {
            super(R.layout.row_sort_friend, data);
            this.mSortContactList = data;
        }

        @Override
        protected void convert(BaseViewHolder helper, BaseSortModel<RoomMember> item) {
            int position;
            if (mRole==3){
                position = helper.getAdapterPosition();
            }else {
                // 添加了头部 ，所以减1
                position = helper.getAdapterPosition() - 1;
            }
            helper.addOnClickListener(R.id.layout_row_sort);
            TextView categoryTitleTv = helper.getView(R.id.catagory_title);
            ImageView avatar_img = helper.getView(R.id.avatar_img);
            TextView nick_name_tv = helper.getView(R.id.nick_name_tv);
            // 根据position获取分类的首字母的Char ascii值
            int section = ListUtil.getSectionmRoomMemberForPosition(mSortRoomMember, position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == ListUtil.getSortRoomMembersPositionForSection(mSortRoomMember, section)) {
                categoryTitleTv.setVisibility(View.VISIBLE);
                categoryTitleTv.setText(mSortContactList.get(position).getFirstLetter());
            } else {
                categoryTitleTv.setVisibility(View.GONE);
            }
            final RoomMember member = mSortContactList.get(position).getBean();
            AvatarHelper.getInstance().displayAvatar(member.getUserId(), avatar_img, true);

            if (coreManager.getSelf().getUserId().equals(member.getUserId())) {
                nick_name_tv.setText(coreManager.getSelf().getNickName());
            } else {
                nick_name_tv.setText(member.getShowName());

               /* Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(), member.getUserId());
                if (friend != null) {
                    nick_name_tv.setText(TextUtils.isEmpty(friend.getRemarkName()) ? friend.getNickName() : friend.getRemarkName());
                } else {
                    nick_name_tv.setText(member.getShowName());
                }*/
            }
        }
    }


}
